/*
Copyright (c) 2008 Nikhil Belsare

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package in.belsare.scheduler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;

public class SchedulerTask {
	final private SchedulerListener listener;
	final private String type;
	final private int manifestId;
	private String taskClasses[];
	private String taskMethod;
	private String processExe;

	final private SchedulerLogger logger = SchedulerLogger.getInstance(); 

	private SchedulerTask(SchedulerListener listener, int manifestId, String type) {
		this.listener = listener;
		this.manifestId = manifestId;
		this.type = type;
	}

	public SchedulerTask(int manifestId, String[] taskClasses, String taskMethod, SchedulerListener listener) {
		this(listener, manifestId,"j");
		this.taskClasses = taskClasses;
		this.taskMethod = taskMethod;
	}

	public SchedulerTask(int manifestId, String processExe, SchedulerListener listener) {
		this(listener, manifestId, "p");
		this.processExe = processExe;
	}

	public int getManifestId() {
		return manifestId;
	}

	public String getType() {
		return type;
	}

	public void execute() {
		// Run sequential chain
		for(String taskClass : taskClasses) {
			if(type.equalsIgnoreCase("j")) {
				PrintStream _err = System.err;
				PrintStream _out = System.out;
				ByteArrayOutputStream outBufStream = new ByteArrayOutputStream();
				PrintStream out = new PrintStream(outBufStream);
				ByteArrayOutputStream errBufStream = new ByteArrayOutputStream();
				PrintStream err = new PrintStream(errBufStream);
				System.setErr(err);
				System.setOut(out);
				try {
					Class tClass = Class.forName(taskClass);
					Method runMethod = tClass.getMethod(taskMethod, (Class[])null);
					if(runMethod != null)
						runMethod.invoke(null, (Object []) null);
				} catch (Exception e) {
					e.printStackTrace(err);
					logger.severe(e.getMessage());
				}
				System.setErr(_err);
				System.setOut(_out);
				listener.taskErrors(manifestId, new StringBuffer(errBufStream.toString()));
				listener.taskOutput(manifestId, new StringBuffer(outBufStream.toString()));
			} else if(type.equalsIgnoreCase("p")) {
				StreamListener eListener = null;
				StreamListener iListener = null;
				try {
					Process p = Runtime.getRuntime().exec(processExe);
					eListener = new StreamListener(p.getErrorStream());
					iListener = new StreamListener(p.getInputStream());
					eListener.start();
					iListener.start();
					p.waitFor();
					eListener.kill();
					iListener.kill();
					eListener.interrupt();
					iListener.interrupt();
				} catch (IOException e) {
					logger.severe(e.getMessage());
				} catch (InterruptedException e) {
					logger.severe(e.getMessage());
				}
				listener.taskErrors(manifestId, eListener.getBuffer());
				listener.taskOutput(manifestId, iListener.getBuffer());
			}
			listener.taskEnded(manifestId);
		}
	}
}
